package com.business.action.wechat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.business.wechat.bean.WeixinConfigBean;
import com.business.wechat.bean.WeixinMenuBean;
import com.business.wechat.service.WeixinUtils;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.service.Service;

/**
 * @author: fengjian
 * @date: 2019/05/12 10:28
 * @description:对接微信公众号的API
 *
 */
@Controller
@RequestMapping("/weixin/menu")
public class WechatMenuAction {

	/**
	 * 
	 */
	@ResponseBody
	@RequestMapping("/list.do")
	public List<WeixinMenuBean> list(HttpServletRequest request, Service service, String menuID) {
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		List<WeixinMenuBean> data = null;
		// 如果没有提供父节点，那么一级节点是所有的微信公众号
		if (menuID == null) {
			data = new ArrayList<>();
			query.setEntityClass(WeixinConfigBean.class);
			query.createSql();
			List<WeixinConfigBean> list = dao.list();
			for (WeixinConfigBean con : list) {
				WeixinMenuBean bean = new WeixinMenuBean();
				bean.setMenuID(con.getId());
				bean.setWeixinID(con.getId());
				bean.setLabel(con.getPublicName());
				data.add(bean);
			}
		} else {
			query.setEntityClass(WeixinMenuBean.class);
			query.createSql("parentID", menuID);
			query.addSql(" ORDER BY sequence asc ");
			data = dao.list();
		}
		return data;
	}

	/**
	 * 
	 */
	@ResponseBody
	@RequestMapping("/save.do")
	public PageBean save(HttpServletRequest request, Service service, WeixinMenuBean bean) {
		PageBean res = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(WeixinMenuBean.class);
		query.createSaveSql(bean);
		if (dao.update() > 0) {
			res.setData(bean);
			res.setMessage("保存成功！");
		} else {
			res.setSuccess(false);
			res.setMessage("保存失败！");
		}
		return res;
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete.do")
	public PageBean delete(HttpServletRequest request, Service service, String menuID) {
		PageBean page = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.createDeleteSql(WeixinMenuBean.class, menuID);
		if (!dao.execute()) {
			page.setSuccess(false);
			page.setMessage("删除失败！");
			return page;
		}
		return page;
	}

	/**
	 * 发布
	 */
	@ResponseBody
	@RequestMapping("/publish.do")
	public PageBean publish(Service service, String weixinID) {
		PageBean page = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		// 根据微信项目编号获取项目其它所有配置
		query.setEntityClass(WeixinConfigBean.class);
		query.createSql(weixinID);
		WeixinConfigBean config = dao.get();
		String url = null;
		WxMpService wxMpService = WeixinUtils.getWeixinBean(config.getProjectName()).getMpService();
		// 获取这个微信公众号的所有的微信菜单
		query.setEntityClass(WeixinMenuBean.class);
		query.createSql("parentID", weixinID);
		query.addSql("order by sequence ASC ");
		List<WeixinMenuBean> list = dao.list();
		List<WeixinMenuBean> root = new ArrayList<>();
		Map<String, WeixinMenuBean> map = new HashMap<>();
		for (WeixinMenuBean m : list) {
			if (m.getParentID().equals(weixinID)) {
				root.add(m);
				map.put(m.getMenuID(), m);
			}
		}
		for (WeixinMenuBean m : list) {
			if (!m.getParentID().equals(weixinID)) {
				map.get(m.getParentID()).getChildren().add(m);
			}
		}
		WxMenu menu = new WxMenu();
		for (WeixinMenuBean m : root) {
			WxMenuButton wb = new WxMenuButton();
			wb.setName(m.getLabel());
			if (m.getChildren().size() == 0) {
				wb.setKey(m.getMenuKey());
				wb.setType(m.getMenuType());
				url = convertUrl(config, m.getMenuUrl());
				url = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, "1");
				System.out.println("微信发布菜单：" + url);
				wb.setUrl(url);
			}
			for (WeixinMenuBean c : m.getChildren()) {
				WxMenuButton wc = new WxMenuButton();
				wc.setName(c.getLabel());
				wc.setKey(c.getMenuKey());
				wc.setType(c.getMenuType());
				url = convertUrl(config, c.getMenuUrl());
				url = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, "1");
				System.out.println("微信发布菜单：" + url);
				wc.setUrl(url);
				wb.getSubButtons().add(wc);
			}
			menu.getButtons().add(wb);
		}
		try {
			wxMpService.getMenuService().menuCreate(menu);
		} catch (WxErrorException e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMessage(e.getMessage());
		}
		return page;
	}

	private String convertUrl(WeixinConfigBean config, String url) {
		if (!url.startsWith("http")) {
			String http = config.getServerUrl();
			String redirectWxUrl = "/any/wechat/" + config.getProjectName() + "/redirectWxUrl.do";
			int index = url.indexOf('?');
			if (index != -1) {
				String page = url.substring(0, index);
				url = page + '&' + url.substring(index + 1);
			}
			url = http + redirectWxUrl + "?to_page=" + url;
		}
		System.out.println("微信发布菜单：" + url);
		return url;
	}

}